package com.starbaba.masterworker;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedDeque;

public class Master {
	//任务队列
	protected Queue<Integer> workQueue = new ConcurrentLinkedDeque<Integer>();
	//worker进程队列
	protected Map<String, Thread> threadMap = new HashMap<String,Thread>();
	//总结果集，ConcurrentHashMap类是线程安全，同时键名对应任务队列的值，确保有序
	protected List<List<Object>> resultList = new ArrayList<>();
	
	/**
	 * 判断所有的子任务是否都已经完成
	 * @return
	 */
	public boolean isComplete(){
		for(Map.Entry<String, Thread> entry : threadMap.entrySet()){
			if(entry.getValue().getState() != Thread.State.TERMINATED){
				return false;
			}
		}
		return true;
	}
	//master的构造，需要一个worker进程的对象，和worker进程的数量
	public Master(Worker worker,int countWorker){
		worker.setWorkQueue(workQueue);
		worker.setResultList(resultList);
		for(int i = 0; i < countWorker; i ++){
			threadMap.put(Integer.toString(i), new Thread(worker,Integer.toString(i)));
		}
	}
	//提交一个任务
	public void submit(Integer job){
		workQueue.add(job);
	}
	//返回总结果集
	public List<List<Object>> getResultList() {
		return resultList;
	}
	//开始运行所有的worker进程，进行处理
	public void execute(){
		
		for(Map.Entry<String, Thread> entry : threadMap.entrySet()){
			entry.getValue().start();
		}
	}	
}